<template>
    <div>
        <el-dialog
                @open="picShow"
                @close="picClose"
                custom-class="uploadDialog"
                title="我的图片"
                :visible.sync="visible"
                :close-on-click-modal="false"
                append-to-body
                width="862px">
            <el-dialog
                    :close-on-click-modal="false"
                    width="700px"
                    title="上传图片"
                    :visible.sync="dialogUploadVisible"
                    append-to-body>
                    <pic-upload-do @finish="finishUpload" :formData.sync="groupForm"></pic-upload-do>
                    <!-- <iframe frameborder="0" :src="uploadUrl" style="width:100%;height:400px;"></iframe> -->
                <!-- <el-upload-sortable 
                        class="upload-demo"
                        :before-upload="beforePicUpload"
                        drag
                        action=""
                        multiple
                    @change="picUpdate">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip">只能上传图片文件，且不超过2m</div>
                </el-upload-sortable> -->
                <!-- <el-upload
                        class="upload-demo"
                        :before-upload="beforePicUpload"
                        drag
                        action=""
                        multiple>
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip">只能上传图片文件，且不超过2m</div>
                </el-upload> -->
                <div slot="footer" class="dialog-footer">
                    <el-button size="mini" type="primary" @click="closeUploadDialog()">关闭</el-button>
                </div>
            </el-dialog>
            <div class="upload-body">
                <div class="category-list-region js-category-list-region">
                    <ul class="category-list">
                        <li class="js-category-item" :class="{active:listQuery.groupCode == item.code}" v-for="item in groups" :key="item.id" @click="viewGroup(item)">
                            {{item.name}}
                            <!--<span>10</span>-->
                            <span v-if="item.code != 'default'">
                                <span @click="editGroup(item)" style="position:relative;margin-right:6px;text-decoration:underline;">编</span>
                                <span @click="deleteGroup(item)" style="position:relative;text-decoration:underline;">删</span>
                            </span>
                        </li>
                        <li style="color:red;font-weight:bold;" @click="createGroup()">+ 添加分类</li>
                    </ul>
                </div>
                <div class="attachment-list-region js-attachment-list-region">
                    <ul class="image-list">
                        <li v-for="item in list" class="image-item js-image-item" @click="setPic(item)" :key="item.id">
                            <div class="image-box" v-bind:style="{ 'background-image': 'url(' + getThumb(item.url) + ')' }"></div>
                            <div class="image-meta">{{item.width}}*{{item.height}}</div>
                            <div class="image-title">{{item.name}}</div>
                            <div class="attachment-selected" v-if="hasSelected(item.url)">
                                <i class="el-icon-check"></i>
                            </div>
                            <a class="js-delete-picture close-modal small hide" @click="removePic(item)">×</a>
                        </li>
                    </ul>
                    <div class="attachment-pagination js-attachment-pagination">
                        <el-row type="flex" justify="space-between">
                            <el-col :span="6">
                                <el-button size="mini" type="primary" @click="upload()">上传图片</el-button>
                            </el-col>
                            <el-col :span="18">
                                <el-pagination
                                        @current-change="handleCurrentChange"
                                        :current-page.sync="listQuery.page"
                                        :page-size="listQuery.num"
                                        layout="total, prev, pager, next"
                                        :total="total">
                                </el-pagination>
                            </el-col>
                        </el-row>
                    </div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                    <el-button size="mini" @click="cancel()">取消</el-button>
                    <el-button size="mini" type="primary" @click="ok()">确定</el-button>
                </span>
        </el-dialog>

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="500px" @close="dialogClose">
            <el-form :model="form" :rules="rules" ref="form" label-width="150px">
                <el-form-item label="分类名称" prop="name">
                    <common-input v-model="form.name" placeholder="请输入分类名称" maxlength="10" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="cancelCat('form')">取消</el-button>
                <el-button size="mini" v-if="dialogStatus=='create'" type="primary" @click="create('form')">确定</el-button>
                <el-button size="mini" v-else type="primary" @click="update('form')">确定</el-button>
            </div>
        </el-dialog>
        
    </div>
</template>
<script>
    // import ElUploadSortable from "el-upload-sortable";
    import {
        fetchUploadGroup,
        uploadSubmit,
        getUploadList,
        getUploadToken,
        createFileGroup,
        editFileGroup,
        deleteFileGroup,
        deleteFile
    } from '../../api/sys'
    import { API_BASE_URL } from '@/config'
    import { getToken,removeToken } from '@/utils/auth'

    export default {
        name: 'pic-list',
        props: {
            imageList: Array,
            showPicDialog: {
                type: Boolean,
                default: false
            },
            maxNum: {
                type: Number,
                default: 1
            }
        },
        components: {
            'pic-upload-do': () => import('@/view/upload/upload.vue'),
            // ElUploadSortable
        },
        watch: {
            showPicDialog(val) {
                this.visible = val
            },
            imageList: {
                immediate: true,
                handler (val) {
                    this.hasSelectedNum = val.length
                },
                deep: true
            }
        },
        data() {
            return {
                rules: {
                    name: [
                        {
                            required: true,
                            message: '请输入分类名称',
                            trigger: 'blur'
                        },
                        {
                            max: 10,
                            message: '名称最多10个字',
                            trigger: 'blur'
                        }
                    ],
                },
                dialogStatus: '',
                dialogFormVisible: false,
                textMap: {
                    update: '编辑分类',
                    create: '新增分类'
                },
                token: "",
                uploader: null,
                visible: this.showPicDialog,
                list: [
                ],
                total: null,
                listLoading: true,
                listQuery: {
                    page: 1,
                    num: 15,
                    name: undefined,
                    groupCode: "default"
                },
                dialogUploadVisible: false,
                groups: [],
                selectedItems: [],
                hasSelectedNum: 0,
                uploadUrl: process.env.BASE_URL + "#/upload/do",
                form: {
                    name: undefined,
                },
                groupForm: {
                    code: "default"
                },
            }
        },
        created() {
            this.token = getToken();
        },
        mounted() {
            // var uploader = WebUploader.create({
            //     // swf文件路径
            //     swf:'../static/webuploader-0.1.5/Uploader.swf',
            //     // 文件接收服务端。
            //     server: 'http://webuploader.duapp.com/server/fileupload.php',
            //     // 选择文件的按钮。可选。
            //     // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            //     pick: '#picker',
            //     // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
            //     resize: false,
            //     //是否开启自动上传
            //     auto:false
            // });
        },
        methods: {
            removePic(item) {
                this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        deleteFile(item.id)
                            .then(() => {
                                this.$message.success("图片删除成功");
                                this.getList();
                            });
                    }).catch(()=>{});

            },
            viewGroup(item) {
                this.listQuery.page = 1;
                this.listQuery.groupCode = item.code;
                this.getList();
            },
            createGroup() {
                this.resetTemp();
                this.dialogStatus = 'create';
                this.dialogFormVisible = true;

            },
            editGroup(item) {
                this.form.id = item.id;
                this.form.name = item.name;
                this.dialogStatus = 'update';
                this.dialogFormVisible = true;
            },
            deleteGroup(item) {
                this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        deleteFileGroup(item.id)
                            .then(() => {
                                this.$message.success("分类删除成功");

                                fetchUploadGroup("image")
                                    .then(response => {
                                        this.groups = response.data

                                    });
                            });
                    }).catch(()=>{});
            },
            resetTemp() {
                this.form = {
                    name: undefined,
                };
            },
            create(formName) {
                const set = this.$refs;
                set[formName].validate(valid => {
                    if (valid) {
                        createFileGroup(this.form)
                            .then(() => {
                                this.dialogFormVisible = false;
                                this.getGroups();
                                this.$message.success("分类创建成功");
                            })
                    } else {
                        return false;
                    }
                });
            },
            update(formName) {
                const set = this.$refs;
                set[formName].validate(valid => {
                    if (valid) {
                        this.dialogFormVisible = false;
                        editFileGroup(this.form).then(() => {
                            this.dialogFormVisible = false;
                            this.$message.success("分类更新成功");

                            fetchUploadGroup("image")
                                .then(response => {
                                    this.groups = response.data

                                });
                        });
                    } else {
                        return false;
                    }
                });
            },
            cancelCat(formName) {
                this.dialogFormVisible = false;
                this.$refs[formName].resetFields();
            },
            dialogClose() {
                this.$refs.form.resetFields();
            },
            finishUpload() {
                this.$message.success("图片已上传");
                this.dialogUploadVisible = false
                this.listQuery.page = 1 //重新读取第一页
                this.getList()
            },
            picUpdate(list){
            },
            getList() {
                this.listLoading = true;
                getUploadList(this.listQuery).then(response => {
                    this.list = response.data ? response.data.list : null;
                    this.total = response.data.total;
                    this.listLoading = false;
                })
            },
            picClose() {
                this.selectedItems = []
                this.$emit("on-close", false);
            },
            cancel() {
                this.visible = false
            },
            upload() {
                this.groupForm = {
                    code: this.listQuery.groupCode
                }
                this.dialogUploadVisible = true;
            },
            
            beforePicUpload(file) {
                if (!/^image\/(jpeg|png|gif|bmp)$/.test(file.type)) {
                    this.$message.error('只能上传图片格式!');
                    return false
                }

                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                    this.$message.error('上传图片大小不能超过 2MB!');
                    return false
                }

                let param = new FormData();
                param.append('file', file);
                param.append("group", this.listQuery.groupCode);
                param.append('mediaType', "image");

                getUploadToken(this.listQuery.groupCode).then((response)=>{
                    param.append('token', response.data);

                    uploadSubmit(param)
                        .then(response => {
                            this.$message.success("图片已上传");
                            this.dialogUploadVisible = false
                            this.listQuery.page = 1 //重新读取第一页
                            this.getList()
                        }).catch(()=>{

                        });
                }).catch(()=>{

                });


                return false
            },
            getGroups() {
                fetchUploadGroup("image")
                    .then(response => {
                        this.groups = response.data

                        this.getList()

                    });
            },
            closeUploadDialog() {
                this.dialogUploadVisible = false
            },
            handleCurrentChange(val) {
                this.listQuery.page = val;
                this.getList();
            },
            hasSelected(url) {
                return this.selectedItems && this.selectedItems.includes(url)
            },
            setPic(item) {
                if(this.selectedItems && this.selectedItems.includes(item.url)) {
                    let index = this.selectedItems.indexOf(item.url)
                    this.selectedItems.splice(index, 1)
                } else {
                    if(!this.selectedItems) {
                        this.selectedItems = []
                    }
                    if(this.maxNum > 0 && (this.selectedItems.length >= this.maxNum || (this.hasSelectedNum + this.selectedItems.length) >= this.maxNum)) {
                        return
                    }

                    this.selectedItems.push(item.url)
                }
            },
            ok() {
                this.$emit("on-selected", this.selectedItems);
                this.cancel()
            },
            getThumb(thumb) {
                return this.$options.filters.thumbnail(thumb);
            },
            picShow() {
                this.getGroups();
            }
        }
    }
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    .upload-body {
        height: 472px;

        .el-pagination {
            text-align: right;
        }

        .attachment-pagination {
            position: absolute;
            bottom: 70px;
            width: 670px;
            padding: 6px;
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            box-sizing: border-box;
            /*background: #f8f8f8*/
        }

        .category-list-region {
            float: left;
            width: 160px;
            height: 472px;
            padding: 9px 0;
            background: #f2f2f2;
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            box-sizing: border-box;
            overflow: hidden
        }

        .category-list-region ul {
            margin: 0;
            padding: 0;
        }

        .category-list-region li {
            position: relative;
            height: 40px;
            line-height: 40px;
            padding: 0 40px 0 15px;
            cursor: pointer;
            text-overflow: ellipsis;
            overflow: hidden;
            margin:0;
            list-style: none;

            &:hover{
                background: #fafafa
            }

            &.active {
                background: #fff
            }

            span {
                position: absolute;
                right: 10px;
                top: 0px;
                color: #999
            }
        }

        .attachment-list-region {
            padding: 20px 20px 10px 180px;
            /*width: 100%*/
        }

        .image-list {
            margin: 0;
            padding: 0;

            .attachment-selected {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                border: 2px solid #F4222D;
                -webkit-box-sizing: border-box;
                -moz-box-sizing: border-box;
                box-sizing: border-box;
                &:after {
                    position: absolute;
                    display: block;
                    content: ' ';
                    right: 0;
                    bottom: 0;
                    border: 14px solid #F4222D;
                    border-left-color: transparent;
                    border-top-color: transparent;
                    z-index: 1;
                }

                i {
                    position: absolute;
                    right: 1px;
                    bottom: 1px;
                    z-index: 2;
                    color: white;
                }
            }

            .image-item {
                position: relative;
                float: left;
                width: 100px;
                height: 100px;
                margin-left: 15px;
                margin-bottom: 30px;
                cursor: pointer;
                list-style: none;
        
                .close-modal {
                    position: absolute;
                    z-index: 91;
                    top: -9px;
                    right: -9px;
                    width: 20px;
                    height: 20px;
                    font-size: 16px;
                    line-height: 18px;
                    color: #fff;
                    text-align: center;
                    cursor: pointer;
                    background: rgba(153,153,153,0.6);
                    border-radius: 10px;
                    display: none;
                }

                &:hover {
                    .close-modal {
                        display:block;
                    }
                }

                .image-box {
                    background-color: #ccc;
                    width: 100px;
                    height: 100px;
                    background-size: cover;
                    background-position: 50% 50%
                }

                .image-meta {
                    position: absolute;
                    width: 100px;
                    height: 25px;
                    line-height: 25px;
                    color: #fff;
                    text-align: center;
                    background: rgba(0,0,0,0.2);
                    bottom: 0
                }

                .image-title {
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    overflow: hidden;
                    margin-top: 5px
                }
            }
        }
    }
</style>